package com.keeson.android_cli.util;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by zhoujiaqi on 2017/10/13.
 */

public class BaseUtils {
    /**
     * 状态栏颜色修改 5.0及以上才可以看到效果  隐藏虚拟按键
     * @param activity
     */
    public static void hideBottomUIMenu(AppCompatActivity activity) {

        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = activity.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            Window window = activity.getWindow();
            View decorView = window.getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }



    }

    /**
     * 键盘隐藏
     * @param v
     * @param event
     * @return
     */
    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            // 获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


    /**
     * 获取无线网卡mac
     * @param context
     * @return
     */
    public synchronized static String getMacid(Context context) {
        WifiManager wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        String WLANMAC = wm.getConnectionInfo().getMacAddress();
        return WLANMAC ;
    }


    //获得独一无二的Psuedo ID
    public static String getUniquePsuedoID() {
        String serial = null;

        String m_szDevIDShort = "35" +
                Build.BOARD.length()%10+ Build.BRAND.length()%10 +

                Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 +

                Build.DISPLAY.length()%10 + Build.HOST.length()%10 +

                Build.ID.length()%10 + Build.MANUFACTURER.length()%10 +

                Build.MODEL.length()%10 + Build.PRODUCT.length()%10 +

                Build.TAGS.length()%10 + Build.TYPE.length()%10 +

                Build.USER.length()%10 ; //13 位

        try {
            serial = Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }




    public static long getSecondMilli(long millis) {
        return millis / 1000 * 1000;
    }



    /**
     * 判断IP格式
     */

    public synchronized static boolean ipCheck(String ip) {
        if (ip != null && !ip.isEmpty()) {
            // 定义正则表达式
            String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
            // 判断IP地址是否与正则表达式匹配
            if (ip.matches(regex)) {
                // 返回判断信息
                return true;
            } else {
                // 返回判断信息
                return false;
            }
        }
        return false;
    }


    /**
     *
     * @param context
     */
    public  static void showInputMethod(Context context) {
        //自动弹出键盘
        InputMethodManager inputManager=(InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        //强制隐藏Android输入法窗口
        // inputManager.hideSoftInputFromWindow(edit.getWindowToken(),0);
    }


    /**
     * URL检查<br>
     * <br>
     * @param pInput     要检查的字符串<br>
     * @return boolean   返回检查结果<br>
     */
    public synchronized static boolean isUrl (String pInput) {
        if(pInput == null){
            return false;
        }
        //String regEx = "^(http|https|ftp)\\://([a-zA-Z0-9\\.\\-]+(\\:[a-zA-Z0-9\\.&%\\$\\-]+)*@)?((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\\-]+\\.)*[a-zA-Z0-9\\-]+\\.[a-zA-Z]{2,4})(\\:[0-9]+)?(/[^/][a-zA-Z0-9\\.\\,\\?\\'\\\\/\\+&%\\$#\\=~_\\-@]*)*$";
        String regEx = "^(http|https|ftp)\\://([a-zA-Z0-9\\.\\-]+(\\:[a-zA-Z0-9\\.&%\\$\\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\\-]+\\.)*[a-zA-Z0-9\\-]+\\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\\:[0-9]+)*(/($|[a-zA-Z0-9\\.\\,\\?\\'\\\\\\+&%\\$#\\=~_\\-]+))*$";
        Pattern p = Pattern.compile(regEx);
        Matcher matcher = p.matcher(pInput);
        return matcher.matches();
    }






    /**
     * BCC校验  除数据头尾外的其他数据的异或运算
     */
/*
    public synchronized static byte getXor(byte[] datas) {
        byte temp = datas[0];
        for (int i = 1; i < datas.length; i++) {
            temp ^= datas[i];
        }
        return temp;
    }


    *//**
     *  刷卡数据校验
     *//*
    public synchronized static boolean CardDataCheck(byte[] datas){
        if(datas.length == 9  &&  (datas[0]&0xff)==2 && (datas[datas.length-1]&0xff)==3){
            byte Xor = datas[datas.length-2];
            LogUtils.i("Xor======", HexDump.toHexString(Xor)+"");

            final byte[] data = new byte[6];
            System.arraycopy(datas, 1, data, 0, 6);
            LogUtils.i("XorData======", HexDump.toHexString(data)+"");

            if(getXor(data) == Xor){
                return true;
            }
        }
        return false;
    }*/

    /**
     * 获取卡数据
     */

    public static byte[] getCardData(byte[] datas){
        byte[] resultData = new byte[4];
        System.arraycopy(datas, 3, resultData, 0, 4);
        return  resultData;
    }



    /**
     * 获取当前时间的字符串
     * 将本机时间 + 时间差，转换成对应格式字符串
     */
    public static String getDateStr() {
        SimpleDateFormat mFormatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        long time = new Date().getTime();
        Date mCurDate = new Date(time);
        return mFormatDate.format(mCurDate);
    }



    /**
     * 比较两个时间（DateTime）
     *
     * @return true是比较时间比被比较时间小或相等，反之则返回false
     */
    public synchronized static boolean comparisonDateT(String forDateTime, String byDateTime) {
        try {
            SimpleDateFormat mFormatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            Date forDt = mFormatDate.parse(forDateTime);
            Date byDt = mFormatDate.parse(byDateTime);
            return forDt.getTime() <= byDt.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }











    /**
     * 精确的减法运算，保留2位小数
     */
    public static String sub(String value1, String value2) {
        BigDecimal b1 = new BigDecimal(verifyNum(value1));
        BigDecimal b2 = new BigDecimal(verifyNum(value2));
        return b1.subtract(b2).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
    }




    public static String getBigValue(String value){
        return new BigDecimal(verifyNum(value)).setScale(4, BigDecimal.ROUND_HALF_UP).toString();
    }

    public static String verifyNum(String value) {
        if (!CommonsUtil.isNumber(value)) {
            value = "0.00";
        }
        return value;
    }


    /**
     * 下载时，查看文件大小
     *
     * @param var0
     */
    public static String getDataSize(long var0) {
        DecimalFormat var2 = new DecimalFormat("###.00");
        return var0 < 1024L ? var0 + "bytes" : (var0 < 1048576L ? var2.format((double) ((float) var0 / 1024.0F))
                + "KB" : (var0 < 1073741824L ? var2.format((double) ((float) var0 / 1024.0F / 1024.0F))
                + "MB" : (var0 < 0L ? var2.format((double) ((float) var0 / 1024.0F / 1024.0F / 1024.0F))
                + "GB" : "error")));
    }



    /**
     * S200灯光控制
     * @param a
     * @param b
     * @param c
     * @param d
     */
    public static void setAllLight(String a, String b, String c, String d) {
        //亮灯
        String led1 = "/sys/class/leds/red/brightness";
        String led2 = "/sys/class/leds/green/brightness";
        String led3 = "/sys/class/leds/blue/brightness";
        try {
            FileOutputStream fRed = new FileOutputStream(led1);
            FileOutputStream fGreen = new FileOutputStream(led2);
            FileOutputStream fWhite = new FileOutputStream(led3);
            FileOutputStream fOff = new FileOutputStream(led3);
            fRed.write(a.getBytes());
            fGreen.write(b.getBytes());
            fWhite.write(c.getBytes());
            fOff.write(d.getBytes());
            fRed = new FileOutputStream(led1);
            fGreen = new FileOutputStream(led2);
            fWhite = new FileOutputStream(led3);
            fOff = new FileOutputStream(led3);
            fRed.close();
            fGreen.close();
            fWhite.close();
            fOff.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }






    /**
     *
     * @param Array
     * @return
     */
    public static byte[]reverseArray(byte[]Array){
        byte[]new_array=new byte[Array.length];
        for(int i=0;i<Array.length;i++){
            new_array[i] = Array[Array.length-i-1];
        }
        return new_array;
    }




    public static String getGender(int gender){
        String str = "";

        if (gender == 1){
            str = "男";
        }else if(gender == 2){
            str = "女";
        }


        return str;
    }

    /**
     * 将List<String>集合 转化为String
     * 如{"aaa","bbb"} To 'aaa','bbb'
     */
    public static String convertListToString(List<String> strlist) {
        StringBuffer sb = new StringBuffer();
        if (strlist!=null) {
            for (int i = 0; i < strlist.size(); i++) {
                if (i == 0) {
                    sb.append("'").append(strlist.get(i)).append("'");
                } else {
                    sb.append(",").append("'").append(strlist.get(i)).append("'");
                }
            }
        }
        return sb.toString();
    }


    public static String convertListToString2(List<String> strlist) {
        StringBuffer sb = new StringBuffer();
        if (strlist!=null) {
            for (int i = 0; i < strlist.size(); i++) {
                if (i == 0) {
                    sb.append(strlist.get(i));
                } else {
                    sb.append(",").append(strlist.get(i));
                }
            }
        }
        return sb.toString();
    }

    /**
     * 返回当前程序版本号
     */
    public static String getAppVersionCode(Context context) {
        int versioncode = 0;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            // versionName = pi.versionName;
            versioncode = pi.versionCode;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versioncode + "";
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName=null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            Log.e("VersionInfo", versionName+"");
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }


    // Gps是否可用
    public static boolean isLocationEnabled(Context context) {
        try {
            LocationManager locationManager = (LocationManager) context.
                    getSystemService(Context.LOCATION_SERVICE);
            return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception e) {
            return false;
        }
    }


    public static boolean getTopApp(Context mContext) {
        String lockAppName = "com.keeson.Pregnant.ui.main.MainActivity";
        String topActivityName = "";
        ActivityManager am = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = am
                .getRunningTasks(1);
        if (runningTasks != null && !runningTasks.isEmpty()) {
            ActivityManager.RunningTaskInfo taskInfo = runningTasks.get(0);
            topActivityName = taskInfo.topActivity.getClassName();
        }
        if (lockAppName.equals(topActivityName)) {
            return true;
        }
        return false;
    }

}
